package com.ants.boot.core.security.service;

import com.ants.boot.core.security.user.LoginUser;
import com.ants.boot.system.domain.SysUser;
import com.ants.boot.system.service.SysRoleService;
import com.ants.boot.system.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 蚂蚁会花呗
 * @date 2022/2/15 15:42
 */
@Service
public class CustomUserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysRoleService sysRoleService;



    @Override
    public UserDetails loadUserByUsername(String username){
        SysUser sysUser = sysUserService.findByUsername(username);
        if (sysUser == null){
            throw new UsernameNotFoundException("账号不存在");
        }
        List<String> roleList = sysRoleService.findByUserId(sysUser.getId());
        List<GrantedAuthority> authorities = roleList.stream()
                .map(SimpleGrantedAuthority::new).collect(Collectors.toList());
        LoginUser loginUser = new LoginUser(username,sysUser.getPassword(),authorities);
        loginUser.setUserId(sysUser.getId());
        loginUser.setUsername(sysUser.getUsername());
        loginUser.setAge(sysUser.getAge());
        loginUser.setAvatar(sysUser.getAvatar());
        loginUser.setEmail(sysUser.getEmail());
        loginUser.setNickName(sysUser.getEmail());
        loginUser.setPhoneNumber(sysUser.getPhoneNumber());
        return loginUser;
    }
}
